const addUserBtn = document.getElementById('add-user')
const doubleBtn = document.getElementById('double')
const showBtn = document.getElementById('show')
const sortBtn = document.getElementById('sort')
const calulateBtn = document.getElementById("calulate")
const personList = document.querySelector('.person-info')
// 用户信息
let data = [];

getRandomUser()
getRandomUser()
getRandomUser()

async function getRandomUser() {
    // 调用生成随机用户信息的api
    const res = await fetch('https://randomuser.me/api');
    const data = await res.json();

    const user = data.results[0];

    const newUser = {
        name: `${user.name.first} ${user.name.last}`,
        money: Math.floor(Math.random() * 1000000)
    };

    // 将信息保存到data中
    addData(newUser)
}

function addData(user) {
    data.push(user);
    // 更新用户列表
    updataDOM();
}


function updataDOM(providedData = data) {
    console.log('update' + JSON.stringify(providedData));
    // 清空之前的数据
    personList.innerHTML = ``;
    providedData.forEach((item) => {
        const liElement = document.createElement('li')
        liElement.innerHTML = `<strong>${item.name}</strong><strong>${formatMoney(item.money)}</span>`
        personList.appendChild(liElement);
    })
}

// 对金额格式化
function formatMoney(money) {
    return '$' + money.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
}

/* 金额翻倍 */
function doubleMoney() {
    console.log(data);
    data = data.map(user => {
        return {
            ...user,
            money: user.money * 2
        }
    })
    console.log(data);
    updataDOM()
}

// 金额大于百万的用户
function showMillionaires() {
    data = data.filter(user => user.money > 1000000);

    updataDOM();
}

// 计算全部用户的金额总数
function calculateWealth() {
    const wealth = data.reduce((acc, user) => (acc += user.money), 0);

    const wealthEl = document.createElement('li');
    wealthEl.classList.add('wealth')
    wealthEl.innerHTML = `<strong>Total Wealth: </strong><span>${formatMoney(wealth)}</span></h3>`;
    personList.appendChild(wealthEl);
}

//   根据金额大小排序
function sortByRichest() {
    console.log(123);
    data.sort((a, b) => b.money - a.money);

    updataDOM();
}
// 绑定事件
addUserBtn.addEventListener('click', getRandomUser)
doubleBtn.addEventListener('click', doubleMoney)
showBtn.addEventListener('click',showMillionaires)
sortBtn.addEventListener('click',sortByRichest)
calulateBtn.addEventListener('click',calculateWealth)